from rest_framework import serializers
from django_redis import get_redis_connection

from oauth.utils import check_access_token
from .models import OAuthQQUser
# serializers.ModelSerializer
# serializers.Serializer

# ModelSerializer没有优势
# Serializer
from users.models import User


class OauthQQUserSerilizer(serializers.ModelSerializer):
	"""
	.对数据进行校验(手机号，密码，短信验证码，openid(处理过的))
		.1短信验证码
		.2openid（处理过的）
		.3根据手机号查询用户信息，判断是否存在
	"""
	access_token = serializers.CharField(label='操作凭证')
	# 邮政编码，身份证号码，邮箱，营业执照，车牌号
	mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
	password = serializers.CharField(label='密码', max_length=20, min_length=8)
	sms_code = serializers.CharField(label='短信验证码')

	def validate(self, attrs):
		# .1短信验证码
		# 1.1用户输入的
		sms_code = attrs.get('sms_code')
		mobile = attrs.get('mobile')
		# 1.2redis的数据
		redis_conn = get_redis_connection('code')
		redis_code = redis_conn.get('sms_%s'%mobile)
		if redis_code is None:
			raise serializers.ValidationError('短信验证码已过期')
		# 1.3对比
		if redis_code.encode() != sms_code:
			raise serializers.ValidationError('验证码不一致')

		# .2openid（处理过的）
		access_token = attrs.get('access_token')

		openid = check_access_token(access_token)
		if openid is None:
			raise serializers.ValidationError('token被篡改')

		attrs['openid'] = openid

		# 3.根据手机号查询用户信息，判断是否存在
		try:
			user = User.objects.get(mobile)
		except User.DoesNotExist:
			# 如果用户不存在 就是创建用户

			# 我们可以在这里创建user
			# 我们把创建user的工作 先留到后边
			pass
		else:
			# 如果用户存在，我们应该校验密码
			if not user.check_password(attrs['password']):
				raise serializers.ValidationError('密码不一致')

			attrs['user'] = user
		return attrs
	# data--> attrs--> validated_data
	def create(self, validated_data):
		user = validated_data.get('user')
		openid = validated_data.get('openid')

		if user is None:
			# 创建用户
			user = User.objects.create(
				username=validated_data.get('mobile'),
				mobile = validated_data.get('mobile'),
				password = validated_data.get('password')
			)

			user.set_password(validated_data.get('passsword'))
			user.save()

		qquser = OAuthQQUser.objects.create(
			user = user,
			openid = openid
		)

		return qquser